package com.zxy.hotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.hotel.entity.Admin;
import com.zxy.hotel.mapper.AdminMapper;
import com.zxy.hotel.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiusi
 * @since 2021-12-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService, UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin == null) {
            throw new UsernameNotFoundException("未找到用户");
        }
        return admin;
    }

    @Override
    public Integer addAmin(String adminName, String adminAccount, String adminPassword, String adminRole) {
        Admin admin = new Admin();
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        adminPassword = passwordEncoder.encode(adminPassword);
        admin.setName(adminName);
        admin.setAccount(adminAccount);
        admin.setPassword(adminPassword);
        admin.setRole(adminRole);
        return adminMapper.insertOne(admin);
    }
}
